package org.keyroy.util;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;

import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.UIManager;

public class UIUtil {
	public static final void setLookAndFeel() {
		try {
			UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
		} catch (Exception e) {
		}
	}

	public static final void center(Component component) {
		Toolkit toolkit = Toolkit.getDefaultToolkit();
		Dimension scmSize = toolkit.getScreenSize();
		int width = component.getWidth(), height = component.getHeight();
		component.setLocation(scmSize.width / 2 - (width / 2), scmSize.height / 2 - (height / 2));
	}

	public static BufferedImage scaleImage(BufferedImage src, int tWidth, int tHeight) {
		if (src.getWidth() == tWidth && src.getHeight() == tHeight) {
			return src;
		}

		double xScale = ((double) tWidth) / ((double) src.getWidth());
		double yScale = ((double) tHeight) / ((double) src.getHeight());
		double scale = Math.min(xScale, yScale);

		double iWidth = (double) src.getWidth() * scale;
		double iHeight = (double) src.getHeight() * scale;
		int width = (int) iWidth + (iWidth % 1d > 0 ? 1 : 0);
		int height = (int) iHeight + (iHeight % 1d > 0 ? 1 : 0);

		BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
		Graphics2D g2d = bufferedImage.createGraphics();
		g2d.scale(scale, scale);
		g2d.drawImage(src, 0, 0, null);
		g2d.dispose();
		return bufferedImage;
	}

	public static final void showPopMenu(Component invoker, int x, int y, String name, ActionListener actionListener) {
		JPopupMenu popupMenu = new JPopupMenu();
		JMenuItem menuItem = new JMenuItem(name);
		menuItem.addActionListener(actionListener);
		popupMenu.add(menuItem);
		popupMenu.show(invoker, x, y);
	}

	public static final void show(Class<? extends Component> class1) {
		try {
			setLookAndFeel();
			Component component = class1.newInstance();
			center(component);
			component.setVisible(true);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
